#coding: utf-8
'''
Created on 30 mars 2011

@author: paraita

    Le retour micro -> haut parleurs fonctionne !

'''


import alsaaudio
#import pyaudio #mac specifique
import time
import os

def ecouteur(nbSecondes=5,fd=1):
    '''
    ecoute le micro et retourne ses donnees vers le fd donné en paramètre
    '''
    inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL)
    inp.setchannels(1)
    inp.setrate(8000)
    inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    inp.setperiodsize(512)
    
    fini = False
    startFlag1 = time.time()
    while not fini:
            l,data = inp.read()
            if l:
                tailleDonneesEcrites = os.write(fd, data)
                print "ecouteur a envoyé ",tailleDonneesEcrites, "octets"
            endFlag1 = time.time()
            if (endFlag1 - startFlag1) >= nbSecondes:
                fini = True
    os.close(fd)
    print "scrutage du micro terminé"
    
def toSpeakers(nbSecondes=5,fd=1):
    
    out = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL)
    out.setchannels(1)
    out.setrate(8000)
    out.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    out.setperiodsize(512)
    
    fini = False
    startFlag2 = time.time()
    
    data = os.read(fd, 512*2)
    
    while not fini:
        while data <> "":
            print "taille des donnees recu ", len(data), "octets"
            out.write(data)
            endFlag2 = time.time()
            if (endFlag2-startFlag2) >= (nbSecondes):
                fini = True
            data = os.read(fd, 512*2)
    os.close(fd)
    print "Ecriture dans les haut parleurs terminé"
        

def makeEchoEffectLive():
    
    rfd,wfd = os.pipe()
    
    pid = os.fork()
    
    if pid == 0:
        os.close(rfd)
        ecouteur(nbSecondes=5,fd=wfd)
    else:
        os.close(wfd)
        toSpeakers(nbSecondes=5,fd=rfd)

'''
def capture_micro_osx(fd=0):
    inp_mac = pyaudio.PyAudio()
    stream = inp_mac.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=8000,
                          input=True,
                          frames_per_buffer=512)
    while True:
        data = stream.read(512)
        if data:
            os.write(fd, data)

def to_speaker_osx(fd=0):
    out_mac = pyaudio.PyAudio()
    stream = out_mac.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=8000,
                          output=True)
    data = os.read(fd, 512*2)
    while True:
        if not data == "":
            stream.write(data)
        data = os.read(fd, 512*2)
'''



